package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjFactorySpare;
import com.zb.mapper.ZjFactorySpareMapper;
import com.zb.service.ZjFactorySpareService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 厂商配件关联表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-04-13
 */
@Service
public class ZjFactorySpareServiceImpl extends ServiceImpl<ZjFactorySpareMapper, ZjFactorySpare> implements ZjFactorySpareService {

    // 保存品牌商家与配件的关联
    @Override
    public void save(Long custAccId, Long spareId, List<Long> factoryIds) {
        deleteBySpareId(spareId);
        if (CollectionUtil.isEmpty(factoryIds)) {
            return;
        }
        List<ZjFactorySpare> factorySpares = new ArrayList<>();
        ZjFactorySpare factorySpare = null;
        for (Long factoryId : factoryIds) {
            factorySpare = new ZjFactorySpare();
            factorySpare.setId(IdWorker.getId());
            factorySpare.setCustAccId(custAccId);
            factorySpare.setFactoryId(factoryId);
            factorySpare.setSpareId(spareId);
            factorySpares.add(factorySpare);
        }
        this.saveBatch(factorySpares);
    }

    // 根据配件ID删除关联的品牌商家
    @Override
    public void deleteBySpareId(Long spareId) {
        QueryWrapper<ZjFactorySpare> wrapper = new QueryWrapper<>();
        wrapper.eq("spare_id", spareId);
        this.remove(wrapper);
    }

    // 根据配件ID删除关联的品牌商家
    @Override
    public void deleteBySpareIds(List<Long> spareIds) {
        if (CollectionUtil.isEmpty(spareIds)) {
            return;
        }
        QueryWrapper<ZjFactorySpare> wrapper = new QueryWrapper<>();
        wrapper.in("spare_id", spareIds);
        this.remove(wrapper);
    }

    // 根据配件ID获取关联的品牌厂商
    @Override
    public List<ZjFactorySpare> getBySpareId(Long spareId) {
        QueryWrapper<ZjFactorySpare> wrapper = new QueryWrapper<>();
        wrapper.select("id", "factory_id")
                .eq("spare_id", spareId);
        return this.list(wrapper);
    }
}
